package P1线性结构;

public class SuffixCalculator {
    public static void main(String[] args) {
        String express = "10 20 2 / 3 * + 2 / 8 + ";
        int result = evalute(express);
        System.out.println(result);
    }

    private static int evalute(String express) {
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        String[] tokens = express.split(" ");
        for (String token : tokens) {
            if (token.length() != 0) {
                if (isOperater(token)) {
                    process(stack, token);
                } else {
                    stack.push(Integer.parseInt(token));
                }
            }
        }
        return stack.pop();
    }

    private static void process(ArrayDeque<Integer> stack, String op) {
        int num1 = stack.pop();
        int num2 = stack.pop();
        if (op.charAt(0) == '+') {
            stack.push(num2 + num1);
        } else if (op.charAt(0) == '-') {
            stack.push(num2 - num1);
        } else if (op.charAt(0) == '*') {
            stack.push(num2 * num1);
        } else {
            stack.push(num2 / num1);
        }
    }

    private static boolean isOperater(String token) {
        return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
    }
}